﻿using Basic.FlowDAL;
using Basic.FlowModel;
using Basic.FlowModel.AuditSign;
using Basic.FlowRemoteModel.Application.Model;
using WeDonekRpc.Helper;

namespace Basic.FlowCollect.lmpl
{
    internal class FlowAuditSignLogCollect : IFlowAuditSignLogCollect
    {
        private readonly IFlowAuditSignLogDAL _BasicDAL;

        public FlowAuditSignLogCollect ( IFlowAuditSignLogDAL basicDAL )
        {
            this._BasicDAL = basicDAL;
        }
        public long[] Clear ( long signFileId )
        {
            var data = this._BasicDAL.Gets(a => a.SignFileId == signFileId, a => new
            {
                a.Id,
                a.FileId
            });
            if ( !data.IsNull() )
            {
                this._BasicDAL.Delete(data.ConvertAll(a => a.Id));
                return data.ConvertAll(a => a.FileId);
            }
            return null;
        }
        public SignFile[] Restore ( long logId, long optItemId )
        {
            SignFile[] files = this._BasicDAL.Gets<SignFile>(a => a.LogId == logId && a.OptItemId == optItemId && a.IsVoid == true);
            if ( !files.IsNull() )
            {
                long[] ids = files.Select(c => c.SignFileId).Distinct().ToArray();
                RestoreSignFile[] signs = this._BasicDAL.GetLastSignFile(ids, optItemId);
                this._BasicDAL.Restore(new SignLogSet
                {
                    Ids = files.ConvertAll(a => a.Id),
                    OptItemId = optItemId,
                    Files = signs
                });
            }
            return files;
        }
        public SignFile[] ToVoid ( long[] itemId, long optItemId )
        {
            SignFile[] files = this._BasicDAL.Gets<SignFile>(a => itemId.Contains(a.SignItemId) && ConstDic.ToVoidSignType.Contains(a.SignType) && a.IsVoid == false);
            if ( !files.IsNull() )
            {
                long[] ids = files.Select(c => c.SignFileId).Distinct().ToArray();
                long[] toVoidId = files.ConvertAll(a => a.Id);
                RestoreSignFile[] signs = this._BasicDAL.GetLastSignFile(ids, toVoidId);
                this._BasicDAL.ToVoid(new SignLogSet
                {
                    Ids = toVoidId,
                    OptItemId = optItemId,
                    Files = signs
                });
            }
            return files;
        }


        public bool TryAdd ( AuditSignFileLog add )
        {
            if ( this._BasicDAL.IsExists(c => c.SignFileId == add.SignFileId && c.FileId == add.FileId) )
            {
                return false;
            }
            this._BasicDAL.Add(add);
            return true;
        }
    }
}
